<?php

namespace App\Http\Controllers\Front;

use App\Models\AdvContent;
use App\Models\AgricGoods;
use App\Models\Article;
use App\Models\VillagePublish;
use App\Models\VillageThings;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\PaperCommit;
use App\Models\PaperFeedback;
use App\Models\PaperLibrary;
 
use App\Models\FarmerFeedback;
class IndexController extends Controller
{
    private $data = array();

    public function __construct(Request $request)
    {
        $this->data['pageTitle'] = '乡通';
    }

    /**
     * 首页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        // 顶部大宽图
        $top_width_adv = AdvContent::getAdvContent(0, 1, 0, 74);

        // banner广告位
        $banner_adv = AdvContent::getAdvContent(0, 1, 0, 62);

        // 轮播广告位 每页3条、共9条
        $rotation_adv = AdvContent::getAdvContent(20, 9);

        // 产业热点 6条
        $chanye_article = Article::pc_article_list(['categort_id' => 4], 6);

        // 农品销售 3条
        $goods = AgricGoods::where('is_show', 1)->orderBy('is_top', 'desc')->orderBy('created_at', 'desc')->take(3)->get(['id', 'acticity_price', 'goods_name', 'goods_img']);

        // 技术推荐 9条
        $jishu_article = Article::pc_article_list(['categort_id' => 5], 9);

        // 普法 9条
        $pufa_article = Article::pc_article_list(['categort_id' => 10], 9);

        // 发现 4条
        $video_article = Article::pc_article_list(['types' => 3], 4);

        // 村务 1条
        $cunwu_article = Article::pc_article_list(['categort_id' => 32], 1);

        // 公告通知 7条
        $tongzhi_article = Article::pc_article_list(['categort_id' => 23], 7);
        foreach ($tongzhi_article as $tongzhi_article_key => &$tongzhi_article_val) {
            // 第一条凑齐两张图片
            if ($tongzhi_article_key == 0) {
                $tongzhi_article_val->all_img_url = Article::pc_article_get_all_imgs($tongzhi_article_val);
            }
        }

        // 大事小情 7条
        $things_data = VillageThings::where('is_show', 1)->with(['region_info'])->orderBy('is_top', 'desc')->orderBy('created_at', 'desc')->take(7)->get();

        // 农品助力 1条,
        $publish_data = VillagePublish::with(['village_pub_admin_author', 'village_pub_author'])->where('check_status', 2)->orderBy('is_top', 'desc')->orderBy('created_at', 'desc')->first();
        if ($publish_data->is_admin) {
            $publish_data->auther = [
                'id' => $publish_data->village_pub_admin_author->id,
                'name' => $publish_data->village_pub_admin_author->name,
                'img' => $publish_data->village_pub_admin_author->avatar_url,
            ];
        } else {
            $publish_data->auther = [
                'id' => $publish_data->village_pub_author->id,
                'name' => $publish_data->village_pub_author->real_name ? $publish_data->village_pub_author->real_name : $publish_data->village_pub_author->user_name,
                'img' => img_url($publish_data->village_pub_author->head_portrait),
            ];
        }

        $this->data['top_width_adv'] = !$top_width_adv->isEmpty() ? $top_width_adv[0] : $top_width_adv;
        $this->data['banner_adv'] = !$banner_adv->isEmpty() ? $banner_adv[0] : $banner_adv;
        $this->data['rotation_adv'] = $rotation_adv;
        $this->data['chanye_article'] = $chanye_article;
        $this->data['goods'] = $goods;
        $this->data['jishu_article'] = $jishu_article;
        $this->data['pufa_article'] = $pufa_article;
        $this->data['video_article'] = $video_article;
        $this->data['cunwu_article'] = $cunwu_article;
        $this->data['tongzhi_article'] = $tongzhi_article;
        $this->data['things_data'] = $things_data;
        $this->data['publish_data'] = $publish_data;
        $this->data['is_index'] = 1;
        return view('front.index.index', $this->data);
    }

    /**
     * 数据大屏
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function data_screen(Request $request, $id = 0)
    {	
		$id=2;
		$library = PaperLibrary::find($id);
		if ($library) {
			// 获得问卷题目
			$paperFeedbacks = PaperFeedback::where('paper_librarie_id', $id)->orderBy('subject_no', 'asc')->get();
			// 获得所有回答
            $paperCommits = PaperCommit::where('paper_librarie_id', $id)->get();
			 // 获得答题总人数
			$userIdArr = array_column($paperCommits->toArray(), 'user_id');
			
			$userNum = count(array_unique($userIdArr));
			 // 处理选项数据
			$dataInfo = [];
			foreach ($paperFeedbacks as $paperFeedbacksKey =>$paperFeedbacksVal) {
				$tmp = [];
				$tmp['title'] = $paperFeedbacksKey + 1 . '：' . $paperFeedbacksVal->subject_title . ($paperFeedbacksVal->is_multiple ? '（多选）' : '（单选）');
				$tmp['sub_title'] = $userNum; // 答题总人数
				$tmp['labels'] = []; // 选项

				// 选项处理
				$subjectSelect = $paperFeedbacksVal->subject_select;
				foreach ($subjectSelect as $subjectSelectVal) {
					$tmp['labels'][] = $subjectSelectVal['num'] . '：' . $subjectSelectVal['content'];
					$tmp['chart_content'][$subjectSelectVal['num']] = 0; // 图表数据
				}

				$tmp['show_num'] = []; // 选项数据
				$dataInfo['id' . $paperFeedbacksVal->id] = $tmp;
			}

			// 处理用户提交数据
			foreach ($paperCommits as $paperCommitsVal) {
				$answer = json_decode($paperCommitsVal->answer, true);
				foreach ($answer as $answerVal) {
					$dataInfo['id' . $paperCommitsVal->paper_feedback_id]['chart_content'][$answerVal] += 1;
				}
			}
			//print_r($dataInfo); die;
			
			//年龄标题//对应年龄人数
			foreach($dataInfo['id77']['labels'] as $k=>$v){
					$age_categories_data[]=mb_substr($v,2);
			}
			foreach($dataInfo['id77']['chart_content'] as $k=>$v){
				$age_data[]=$v;
			}
			$data['age_categories_data'] = $age_categories_data;
			$data['age_data'] = $age_data;
			$this->data['age_categories_data']=$age_categories_data;
			$this->data['age_data']=$age_data;
			//男女
			foreach($dataInfo['id78']['labels'] as $k=>$v){
				$arr=array();
				$arr[]=mb_substr($v,2);
				$arr[]=round($dataInfo['id78']['chart_content'][mb_substr($v,0,1)]/$dataInfo['id78']['sub_title'],2)*100;
				$sex_data[]=$arr;
			}
			$data['sex_data'] = $sex_data;
			 
			$this->data['sex_data']=$sex_data;
			//教育
			foreach($dataInfo['id79']['labels'] as $k=>$v){
				$arr=array();
				$arr[]=mb_substr($v,2);
				$arr[]=round($dataInfo['id79']['chart_content'][mb_substr($v,0,1)]/$dataInfo['id79']['sub_title'],2)*100;
				$education_data[]=$arr;
			}
			$data['education_data'] = $education_data;
			$this->data['education_data']=$education_data;
			//从业结构
			foreach($dataInfo['id81']['labels'] as $k=>$v){
					$job_categories_data[]=array('text'=>mb_substr($v,2));
			}
			foreach($dataInfo['id81']['chart_content'] as $k=>$v){
				$job_data[]=$v;
			}
			$data['job_categories_data'] = $job_categories_data;
			$data['job_data'] = $job_data;
				$this->data['job_categories_data']=$job_categories_data;
				$this->data['job_data']=$job_data;
			//农业从业人数
			foreach($dataInfo['id82']['labels'] as $k=>$v){
				$nongye_data[]=array('value'=>$dataInfo['id82']['chart_content'][mb_substr($v,0,1)],'name'=>mb_substr($v,2).$dataInfo['id82']['chart_content'][mb_substr($v,0,1)].'人');
			}
			$nongye_data[]=array('value'=>$dataInfo['id81']['chart_content']['B'],'name'=>"畜牧业".$dataInfo['id81']['chart_content']['B'].'人');
			$data['nongye_data'] = $nongye_data;
			$this->data['nongye_data']=$nongye_data;
			
			
			$dataInfo['id88']['keyval']=array();
			//家庭年均收入
			foreach($dataInfo['id88']['labels'] as $k=>$v){
				if(preg_match_all('/\d+/',$v,$arr)){
					//提取选项答案中的数字 算均值
					$dataInfo['id88']['keyval'][]=round(array_sum($arr[0])/count($arr[0]));
				}
			}
			$sindex=0;
			$sum=0;
			foreach($dataInfo['id88']['chart_content'] as $k=>$v){
				$sum+=$v*$dataInfo['id88']['keyval'][$sindex];
				$sindex++;
			}
			$junzhi=round($sum/$dataInfo['id88']['sub_title']);
			$data['junzhi']=$junzhi;
			$this->data['junzhi']=$junzhi;
			//农业占比
			foreach($dataInfo['id89']['labels'] as $k=>$v){
				if(preg_match_all('/\d+/',$v,$arr)){
					//提取选项答案中的数字 算均值
					$dataInfo['id89']['keyval'][]=round(array_sum($arr[0])/count($arr[0]));
				}
			}
			 
			$zindex=0;
			$zsum=0;
			foreach($dataInfo['id89']['chart_content'] as $k=>$v){
				$zsum+=$v*$dataInfo['id89']['keyval'][$zindex];
				$zindex++;
			}
			$zhanbi=round($zsum/$dataInfo['id89']['sub_title']);
			$chanye_renjun=array(
				array('value'=>$zhanbi),
				array('value'=>(100-$zhanbi))
			);
			$data['chanye_renjun']=$chanye_renjun;
			$data['zhanbi']=$zhanbi;
			$this->data['chanye_renjun']=$chanye_renjun;
			$this->data['zhanbi']=$zhanbi;
			//子女教育 
			foreach($dataInfo['id97']['labels'] as $k=>$v){
				$arr=array();
				$arr['name']=mb_substr($v,2);
				$arr['value']=round($dataInfo['id97']['chart_content'][mb_substr($v,0,1)]/$dataInfo['id97']['sub_title'],2)*100;
				$shenghuo_jiaoyu_data[]=$arr;
			}
			$data['shenghuo_jiaoyu_data']=$shenghuo_jiaoyu_data;
			$this->data['shenghuo_jiaoyu_data']=$shenghuo_jiaoyu_data;
			$carr=array('F5B84D','9BD5F4','1B52A3','26989E','F0853C');
			//出行方式 id101  shenghuo_chuxing_data = [{y:30,h: 50,color:'#'}, {y: 10,h: 10,color:'#'},{y: 15,h: 20,color:'#'},{y: 20,h: 30,color:'#'},{y: 25,h: 40,color:'#'}];
			foreach($dataInfo['id101']['labels'] as $k=>$v){
				$arr=array();
				$arr['y']=round($dataInfo['id101']['chart_content'][mb_substr($v,0,1)]/$dataInfo['id101']['sub_title'],2)*100;
				$arr['h']=$arr['y']>30?$arr['y']+10:$arr['y']+5;
				$arr['color']='#'.$carr[$k];
				$shenghuo_chuxing_data[]=$arr;
				$chuxing_data[]=mb_substr($v,2);
			}
			
			$data['shenghuo_chuxing_data']=$shenghuo_chuxing_data;
			$this->data['chuxing_data']=$chuxing_data;
			//文化设施
			foreach($dataInfo['id111']['labels'] as $k=>$v){
				$wenhua[]=mb_substr($v,2);
			}
			foreach($dataInfo['id111']['chart_content'] as $k=>$v){
				$wenhuasheshi_data[]=$v;
			}
			$data['wenhuasheshi_data']=$wenhuasheshi_data;
			$this->data['wenhua']=$wenhua;
			//满意度计算  生活环境
			$keyv=0;
			$sum=0;
			foreach($dataInfo['id93']['chart_content'] as $k=>$v){
				$keyv++;
				$sum+=$v*$keyv;
			}
			$shenghuokey=round($sum/$dataInfo['id93']['sub_title'])-1;
			//供电
			$keyv=0;
			$sum=0;
			foreach($dataInfo['id103']['chart_content'] as $k=>$v){
				$keyv++;
				$sum+=$v*$keyv;
			}
			$gongdiankey=round($sum/$dataInfo['id103']['sub_title'])-1;
				
			//医疗
			$keyv=0;
			$sum=0;
			foreach($dataInfo['id96']['chart_content'] as $k=>$v){
				$keyv++;
				$sum+=$v*$keyv;
			}
			$yiliaokey=round($sum/$dataInfo['id96']['sub_title'])-1;
			$manyi=[mb_substr($dataInfo['id93']['labels'][$shenghuokey],2),mb_substr($dataInfo['id103']['labels'][$gongdiankey],2),mb_substr($dataInfo['id96']['labels'][$yiliaokey],2)];
			$data['manyi']=$manyi;
			$data['manyif']=array('生活环境','供电','医疗');
			
			//就医方式 id95

			
			 
		}
		//
		$zcnum=Article::where('category_id',8)->whereIn('region_id',array(0,1))->count();
		 $this->data['zcnum']=$zcnum;
		$tznum=Article::where('category_id',23)->whereIn('region_id',array(0,1))->count();
		 $this->data['tznum']=$tznum;
		$pfnum=Article::where('category_id',10)->whereIn('region_id',array(0,1))->count();
		 $this->data['pfnum']=$pfnum;
		$dznum=Article::whereIn('category_id',array(14,15))->whereIn('region_id',array(0,1))->count();
		 $this->data['dznum']=$dznum;		
		$fknum=	FarmerFeedback::whereIn('region_id',array(0,1))->count();
		 $this->data['fknum']=$fknum;
		$gznum=Article::where('category_id',34)->whereIn('region_id',array(0,1))->count();
		 $this->data['gznum']=$gznum;	
		$this->data['data']=json_encode($data);
        return view('front.data_screen.index',$this->data);
    }
}
